package com.generalbackend.controller;

import com.generalbackend.common.constants.Constants;
import com.generalbackend.common.model.CommonResult;
import com.generalbackend.common.response.Response;
import com.generalbackend.common.response.ResponseBuilder;
import com.generalbackend.common.util.ClientUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * @author tim.xie
 * @date 2021/11/29 17:04
 */
@Slf4j
@RestController
public class LoginController {

    @ApiOperation(httpMethod = "GET",value = "提醒去登录页面")
    @RequestMapping(value = "/api/toLogin" ,method = RequestMethod.GET)
    public Response toLogin(){
        return ResponseBuilder.NOT_LOGIN.build();
    }

    @ApiOperation(httpMethod = "POST",value = "登录成功提醒去首页")
    @RequestMapping(value = "/api/toHome" ,method = RequestMethod.POST)
    public Response toHome(){
        return ResponseBuilder.LOGIN_SUCCESS.data("/home").build();
    }

    @ApiOperation(httpMethod = "POST",value = "登录失败")
    @RequestMapping(value = "/api/failureLogin", method = RequestMethod.POST)
    public CommonResult failureLogin(){
        return CommonResult.errorCommonResult("登录失败,输入的帐号或者密码错误!");
    }

    @ApiOperation(httpMethod = "POST", value = "登出")
    @RequestMapping(value = "/api/logout", method = RequestMethod.POST)
    public Object logout(HttpSession session) {
        if(session.getAttribute(Constants.USER_INFO) != null) {
            String username = ClientUtil.getUser().getName();
            session.removeAttribute(Constants.USER_INFO);
            session.removeAttribute(Constants.USER_ID);
            session.removeAttribute(Constants.MENUS);
            session.invalidate();
            log.info("登出成功 {}", username);
        }else {
            log.warn("登出超时");
            return ResponseBuilder.NOT_LOGIN.build();
        }
        return ResponseBuilder.LOGOUT_SUCCESS.build();
    }

}
